package com.tbit.uqbike.service.business.impl;

import com.tbit.uqbike.object.pojo.AccountUser;
import com.tbit.uqbike.object.pojo.PatrolLog;
import com.tbit.common.entity.pojo.vo.DateResult;
import com.tbit.uqbike.object.pojo.statistics.ExportPowerLog;
import com.tbit.uqbike.service.business.PatrolLogService;
import com.tbit.uqbike.webmanager.dao.core.AccountUserDao;
import com.tbit.uqbike.webmanager.dao.log.PatrolLogDao;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.utils.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 巡检日志Service业务层处理
 *
 * @author jing
 * @date 2021-04-29
 */
@Service
public class PatrolLogServiceImpl implements PatrolLogService {
    @Autowired
    private PatrolLogDao patrolLogDao;
    @Autowired
    private AccountUserDao accountUserDao;


    /**
     * 查询巡检日志列表
     *
     * @param patrolLog 巡检日志
     * @return 巡检日志
     */
    @Override
    public List<PatrolLog> selectPatrolLogList(PatrolLog patrolLog) {
        List<PatrolLog> patrolLogs = patrolLogDao.selectPatrolLogList(patrolLog);
        patrolLogs.forEach(p -> {
            p.setAccountUser(accountUserDao.getAccountUserById(p.getAccountUserId()));
        });
        return patrolLogs;
    }

    @Override
    public List<DateResult> statisticsByTime(PatrolLog patrolLog) {
        List<String> daysStr = DateTimeUtil.findDaysStr(DateTimeUtil.formatDateYMD(patrolLog.getStartTime()), DateTimeUtil.formatDateYMD(patrolLog.getEndTime()));
        List<Map<String, Object>> maps = patrolLogDao.statisticsByTime(patrolLog);
        Map<Object, Object> dateMap = maps.stream().collect(Collectors.toMap(map -> (String) map.get("date"), map -> map.get("total"), (x1, x2) -> x1));
        List<DateResult> result = new ArrayList<>();
        daysStr.stream().forEach(day -> {
            DateResult dateResult = new DateResult();
            dateResult.setDate(day);
            dateResult.setTotal(dateMap.containsKey(day) ? ((Long) dateMap.get(day)).intValue() : 0);
            result.add(dateResult);
        });
        return result;
    }

    @Override
    public List<ExportPowerLog> selectByType(PatrolLog patrolLog) {
        List<ExportPowerLog> maps = patrolLogDao.selectByType(patrolLog);
        maps.forEach(p -> {
            if (StringUtils.isNotNull(p)) {
                AccountUser accountUser = accountUserDao.getAccountUserById(p.getAccountUserId());
                if (accountUser != null && StringUtils.isNotEmpty(accountUser.getPhone())) {
                    p.setPhone(accountUser.getPhone());
                }

            }
        });
        return maps;
    }

}
